#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk, gobject
import os, imp
import fileeditor

class firstrundialog:

    def __init__(self, ui):
    
        try:
            self.config = fileeditor.FileEditor('config.py')   
        except:
            import preferencesdialog
            preferencesdialog.preferencesdialog.create_default_config()
            self.config = fileeditor.FileEditor('config.py')  
        
        # Store the gui in a var.
        self.ui = ui
        
        self.ui.get_object('firstrun_page2_exec_chooser').set_filename(self.config.phenny_exec)
        self.ui.get_object('firstrun_page2_configdir_chooser').set_filename(self.config.configdir)
        
        # Enable the "Next" button.
        self.ui.get_object('firstrun').set_page_complete(self.ui.get_object('firstrun').get_nth_page(0), True)
        self.ui.get_object('firstrun').set_page_complete(self.ui.get_object('firstrun').get_nth_page(2), True)
    
    def event_prepare(self, assistant, page):
        
        if self.ui.get_object('firstrun').get_current_page() == 2:
            self.ui.get_object('firstrun_page3_exec_value').set_text(self.ui.get_object('firstrun_page2_exec_chooser').get_filename() or '')
            self.ui.get_object('firstrun_page3_configdir_value').set_text(self.ui.get_object('firstrun_page2_configdir_chooser').get_filename() or '')
        
        self.check_page(None)
    
    def event_apply(self, assistant):
        
        self.config.phenny_exec = self.ui.get_object('firstrun_page2_exec_chooser').get_filename()
        self.config.phenny_configdir = self.ui.get_object('firstrun_page2_configdir_chooser').get_filename()
        
        f = open('config.py', 'w')
        f.write(str(self.config))
        f.close()
        
    def event_close(self, assistant):
        assistant.hide()
    
    def event_cancel(self, assistant):
        assistant.hide()
    
    def check_page(self, chooser):
        
        if self.ui.get_object('firstrun').get_current_page() == 1:
            
            os.access(self.ui.get_object('firstrun_page2_exec_chooser').get_filename(), os.X_OK) and [self.ui.get_object('firstrun_page2_exec_error').hide()] or self.ui.get_object('firstrun_page2_exec_error').show()
            os.access(self.ui.get_object('firstrun_page2_configdir_chooser').get_filename(), os.W_OK|os.R_OK) and [self.ui.get_object('firstrun_page2_configdir_error').hide()] or self.ui.get_object('firstrun_page2_configdir_error').show()
            
            if os.access(self.ui.get_object('firstrun_page2_exec_chooser').get_filename(), os.X_OK) and \
            os.access(self.ui.get_object('firstrun_page2_configdir_chooser').get_filename(), os.W_OK|os.R_OK):
                self.ui.get_object('firstrun').set_page_complete(self.ui.get_object('firstrun').get_nth_page(1), True)
        
    
    def run(self):
        self.ui.get_object('firstrun').show()
